<template>
  <div class="main" v-loading="loading">
    <div>
      <!-- 标题的插槽 -->
      <slot></slot>
    </div>

    <!-- 菜单区域 -->
    <div>
      <!-- 已经登录的情况 -->
      <div v-if="islogin">
        <el-dropdown @command="docommand">
          <div class="menu">
            <el-avatar :src="userlogo" :size="40"></el-avatar>
          </div>

          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                ><el-icon><User /></el-icon>{{ userinfo.tbUser.username }}</el-dropdown-item
              >

              <el-dropdown-item divided command="home"
                ><el-icon><HomeFilled /></el-icon>返回首页</el-dropdown-item
              >

              <el-dropdown-item divided command="logout"
                ><el-icon><CloseBold /></el-icon>退出登录</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <!-- 没有登录的情况 -->
      <div v-if="!islogin">
        <el-button-group>
          <el-button @click="loginVisible = true" type="primary">登录 </el-button>
          <el-button @click="regVisible = true" type="success">注册</el-button>
          <el-button @click="router.push('/')" type="danger">返回首页</el-button>
        </el-button-group>
      </div>
    </div>
  </div>

  <!-- 登录的对话框 -->
  <el-dialog title="用户登录" v-model="loginVisible">
    <div>
      <LoginComp @login-change="loginVisible = false"></LoginComp>
    </div>
  </el-dialog>

  <!-- 注册的对话框 -->
  <el-dialog title="用户注册" v-model="regVisible">
    <div>
      <RegComp @reg-success="reg"></RegComp>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { api } from '@/js/ajax'
import { storeToRefs } from 'pinia'
import { userstore } from '@/stores/userinfo'
import LoginComp from './LoginComp.vue'
import RegComp from './RegComp.vue'
import { useRouter } from 'vue-router'

const router = useRouter()

const { islogin, userinfo, userlogo } = storeToRefs(userstore())
const { updateUserInfo } = userstore()

const loading = ref(false)
const loginVisible = ref(false)
const regVisible = ref(false)
const docommand = (command) => {
  if (command == 'logout') {
    logout()
  } else if (command == 'home') {
    router.push('/')
  }
}

const logout = () => {
  loading.value = true
  api.delete('/auth', {}, () => {
    updateUserInfo(() => {
      loading.value = false
    })
  })
}

const reg = () => {
  regVisible.value = false
  loginVisible.value = true
}
</script>

<style scoped>
.main {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.5rem 1rem;
}
.menu {
  display: flex;
  align-items: center;
}
.menu img {
  display: block;
  height: 3rem;
  width: auto;
}
.el-tooltip__trigger {
  outline: none;
}
</style>
